package com.monitor;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.monitor.api.ApiUtil;
import com.monitor.gray.GrayUtil;
import com.monitor.secret.SecretUtil;
import com.system.comm.utils.FrameSpringBeanUtil;

/**
 * Monitor的工具类
 * @author yuejing
 * @date 2019年4月4日 上午9:08:47
 */
public class MonitorUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(MonitorUtil.class);

	private Environment env;
	/** 是否打开灰度服务 */
	public static boolean isOpenGray = true;
	/** 是否打开Api服务 */
	public static boolean isOpenApi = true;
	/** 是否打开同步秘钥服务 */
	public static boolean isOpenSecret = true;

	public MonitorUtil(Environment env) {
		this.env = env;
	}

	/**
	 * 初始化模块
	 */
	public void init() {
		LOGGER.info("发送系统的API可请求的方法");
		/*ApiUtil.prjId = MsConfig.getClientId();
		ApiUtil.prjToken = MsConfig.getSercret();*/
		final String appName = env.getProperty("spring.application.name");
		ThreadPoolTaskExecutor task = FrameSpringBeanUtil.getBean(ThreadPoolTaskExecutor.class);
		if (isOpenApi) {
			task.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(10 * 1000);
					} catch (InterruptedException e) {
						LOGGER.error(e.getMessage());
					}
					ApiUtil.init(appName);
				}
			});
		}

		task.execute(new Runnable() {
			@Override
			public void run() {
				ScheduledExecutorService service = new ScheduledThreadPoolExecutor(2, new ThreadFactory() {
					@Override
					public Thread newThread(Runnable r) {
						Thread thread = new Thread(r);
						LOGGER.info("初始MonitorUtil[同步密钥/同步灰度服务]的线程:" + thread.getName());
						return thread;
					}
				});
				//线程，每隔30秒调用一次
				Runnable runnable = new Runnable() {
					public void run() {
						if (isOpenSecret) {
							SecretUtil.sync();
						}
						if (isOpenGray) {
							GrayUtil.sync();
						}
					}
				};
				// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
				service.scheduleAtFixedRate(runnable, 10, 30, TimeUnit.SECONDS);
			}
		});
	}
}
